package com.cenjiawen.common;

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hashids.Hashids;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import com.jfinal.kit.HttpKit;
import com.jfinal.kit.LogKit;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.jfinal.plugin.redis.RedisPlugin;
import com.utils.PathUtils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.io.file.FileWriter;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

public class DXUtils {

	public static void main(String[] args) {
		// try {
		// DXUtils dxUtils = new DXUtils();
		// // dxUtils.checkIm("+8613600329292");
		// // dxUtils.startWS();
		//
		// dxUtils.clearConversations();
		// // dxUtils.run();
		// // dxUtils.del("+8613631290232");
		// } catch (Exception e) {
		// e.printStackTrace();
		// }

		final Hashids piaoHashids = new Hashids("piao", 8);
		final String TESTING_CODE = "8XyO5ew5";
		System.out.println(piaoHashids.decode(TESTING_CODE)[0]);
	}

	private Cache cache;// = Redis.use();

	public DXUtils() {

		RedisPlugin rp = new RedisPlugin("myRedis", "localhost");
		// 与web下唯一区别是需要这里调用一次start()方法
		rp.start();
		cache = Redis.use();
	}

	WebSocketClient mWs;

	public void stopWS() {
		mWs.close();
	}

	public void startWS() throws URISyntaxException {
		FileWriter fileWriter = new FileWriter(PathUtils.getFile("logs", "smslog.txt"));
		FileWriter body = new FileWriter(PathUtils.getFile("logs", "smsbodylog.txt"));
		FileWriter statusinfo = new FileWriter(PathUtils.getFile("logs", "smsstatusinfolog.txt"));

		String url = "ws://" + ip + ":333/service";
		URI uri = new URI(url);
		mWs = new WebSocketClient(uri) {
			@Override
			public void onOpen(ServerHandshake serverHandshake) {
				System.out.println("onOpen");
			}

			@Override
			public void onMessage(String s) {
				System.out.println("onMessage: " + s);
				body.append(DateUtil.now() + "\n");
				body.append(s + "\n");
				JSONArray array = JSONUtil.parseArray(s);
				JSONObject jsonObject = JSONUtil.parseObj(array.toArray()[0]);
				// JSONObject jsonObject = JSONUtil.parseObj(s);
				String event = jsonObject.getStr("event");
				if (!"preferredService".equals(event)) {
					return;
				}
				String recipHashID = jsonObject.getStr("recipHashID");
				int prefServ = jsonObject.getInt("prefServ");
				statusinfo.append(recipHashID + " " + (prefServ == 1 ? "成功" : "失败") + "\n");
				if (cache.get(recipHashID) != null) {
					return;
				}
				if (prefServ == 1) {
					cache.setex(recipHashID, 10000, recipHashID);
					fileWriter.append(recipHashID + " 成功\n");
					System.out.println(recipHashID + " 成功\n");
				}
			}

			@Override
			public void onClose(int i, String s, boolean b) {
				System.out.println("onClose");
				try {
					startWS();
				} catch (URISyntaxException e1) {
					e1.printStackTrace();
				}
			}

			@Override
			public void onError(Exception e) {
				System.out.println("onError");
				e.printStackTrace();
				try {
					startWS();
				} catch (URISyntaxException e1) {
					e1.printStackTrace();
				}
			}
		};
		mWs.connect();
	}

	public void clearConversations() throws URISyntaxException {
		System.out.println("Clear");
		String url = "http://" + ip + ":333/getInitialContactList.srv?_=" + System.currentTimeMillis();
		String response = HttpUtil.get(url);
		JSONArray array = JSONUtil.parseArray(response);
		for (Object object : array) {
			JSONObject jsonObject = new JSONObject(object);
			// System.out.println(jsonObject);
			String hash = jsonObject.getStr("hash");
			if (cache.get(hash) != null) {
				continue;
			}
			int prefserv = jsonObject.getInt("prefserv");
			System.out.println(hash + " " + prefserv);
			checkIm(hash);
			ThreadUtil.safeSleep(10000);
		}
		System.out.println();
	}

	public void checkIm(String number) {
		send(number, "", false);
		// new Thread(new Runnable() {
		//
		// @Override
		// public void run() {
		// ThreadUtil.safeSleep(500);
		// check(number);
		// }
		// }).start();
	}

	public void del(String number) {
		String url = "http://" + ip + ":333/deleteConversation.srv";
		HttpRequest request = HttpUtil.createPost(url);
		request.form("hashid", URLEncoder.encode(number));
		System.out.println(request.execute().body());
	}

	public void ws() {
		try {
			// ws://192.168.199.245:333/service
			// 这里用的binance的socket接口，国内调用需要VPN，使用换成你的就行
			// String url = "wss://stream.binance.com:9443/ws/ethbtc@ticker";
			// String url = "wss://stream.binance.com:9443/ws/ethbtc@depth20";
			String url = "ws://192.168.199.245:333/service";
			URI uri = new URI(url);
			WebSocketClient mWs = new WebSocketClient(uri) {
				@Override
				public void onOpen(ServerHandshake serverHandshake) {
					System.out.println("onOpen");
				}

				@Override
				public void onMessage(String s) {
					System.out.println("onMessage: " + s);
				}

				@Override
				public void onClose(int i, String s, boolean b) {
					System.out.println("onClose");
				}

				@Override
				public void onError(Exception e) {
					System.out.println("onError");
					e.printStackTrace();
				}
			};
			mWs.connect();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// fk922(修远电话)
	// private String ip = "192.168.50.62";
	// private String ip = "192.168.199.210";
	// ugg9090(可用)
	private String ip = "192.168.50.158";
	// // private String ip = "192.168.199.175";
	// private String ip = "192.168.199.245";
	// ugg345@hotmail.com
	// private String ip = "192.168.199.181";
	// private String ip = "192.168.50.100";
	// fk930c@gmail.com

	// ugg588@outlook.com
	public void run() throws URISyntaxException {
		String im = "+8613631290232";
		// 133
		im = "+8613392887192";
		im = "+8613631233530";
		// im = "+8613631290232";
		// im = "591030401@qq.com";
		// 峰哥
		// im = "+8618565670619";
		// 修远
		// im = "18925364423";

		// im = "+8613714988831";
		// im = "+8613632928689";
		// im = "+8613631512385";
		// PropKit.use(PathUtils.getFile("logs", "content.txt"));

		// FileReader reader = new
		// FileReader("/Users/cen/Downloads/numbers.txt");
		FileReader reader = new FileReader(PathUtils.getFile("logs", "numbers.txt"), "utf-8");
		FileWriter result = new FileWriter(PathUtils.getFile("logs", "result.txt"), "utf-8");
		List<String> lines = reader.readLines();
		int count = 0;
		int sucCount = 0;
		int failCount = 0;
		clearConversations();
		// for (String string : lines) {
		// // send(mobile, "", false);
		// // ThreadUtil.safeSleep(200);
		// // if (count % 10 == 0) {
		// // send(im, "content" + count, true);
		// // return;
		// // }
		// // check(mobile);
		// // del(mobile);
		// }
		System.out.println(lines.size());
		String content = new FileReader(PathUtils.getFile("logs", "content.txt"), "utf-8").readString();
		// content = "生日快乐啊";
		// send("+86" + "18666578952", content, true);
		// for (String string : lines) {
		// send("+86" + string, content, false);
		// ThreadUtil.safeSleep(3000);
		// if (count++ == 10) {
		// }
		// }
		// send(im, "content", true);
		// check(im);
	}

	private FileWriter fileWriter = new FileWriter(PathUtils.getFile("logs", "sms.txt"));

	public void check(String mobile) {
		String number = mobile;
		String url = "http://" + ip + ":333/getMessages.srv?hashid=" + URLEncoder.encode(number)
				+ "&date=0&shouldReset=1&resetHashID=" + URLEncoder.encode(number) + "&_=" + System.currentTimeMillis();
		System.err.println(url);
		String response = HttpKit.get(url);
		try {
			fileWriter.append(mobile + "\n");
			JSONArray jsonarray = JSONUtil.parseArray(response);
			JSONObject jsonObject = jsonarray.getJSONObject(jsonarray.size() - 1);
			boolean isSent = jsonObject.getBool("isSent");
			String isIM = jsonObject.getStr("isIM");
			String isRead = jsonObject.getStr("isRead");
			String isDelivered = jsonObject.getStr("isDelivered");
			// System.out.println(jsonObject);
			System.out.println("check: " + mobile);
			System.out.println("isSent: " + isSent);
			System.out.println("isIM: " + isIM);
			System.out.println("isRead: " + isRead);
			System.out.println("isDelivered: " + isDelivered);
			JSONArray messageParts = jsonObject.getJSONArray("messageParts");
			JSONObject msg = JSONUtil.parseObj(messageParts.toArray()[0]);
			// for (Object object : messageParts) {
			// System.out.println(object);
			// }
			// System.out.println(msg);
			// System.out.println(messageParts.size());
			// System.out.println(messageParts.toString());
			String text = msg.getStr("text");
			// System.out.println("text: " + text);
			fileWriter.append("isSent: " + isSent + "\n");
			fileWriter.append("isIM: " + isIM + "\n");
			fileWriter.append("isRead: " + isRead + "\n");
			fileWriter.append("isDelivered: " + isDelivered + "\n");
			// System.out.println(response);
		} catch (Exception e) {
			System.out.println(response);
			LogKit.info("check error");
			fileWriter.append(mobile + "error \n");
		}
	}

	public void init() {
		String url = "http://192.168.50.158:333/getInitialContactList.srv?_=1546614971152";
	}

	public void send(String mobile, String content, boolean isSend) {
		String number = mobile;
		Map<String, Object> paramMap = new HashMap<>();
		paramMap.put("hashid", number);
		paramMap.put("reqUID", "z1al");
		paramMap.put("recipients", number);
		paramMap.put("file-name", "");
		paramMap.put("text", "abc");
		String url = "http://" + ip + ":333/sendMessage.srv";
		// url = "http://192.168.50.158:333/sendMessage.srv";
		// System.out.println(url);
		// HttpRequest req = HttpUtil.createPost(url);
		// req = req.form(paramMap);
		// System.out.println(req);
		// System.out.println(req.execute().body());
		// String result2 = HttpRequest.post(url)// 头信息，多个头信息多次调用此方法即可
		// .form(paramMap)// 表单内容
		// .timeout(20000)// 超时，毫秒
		// .execute().body();

		HttpRequest request = HttpUtil.createPost(url);
		// request.contentType(HttpRequest.TIMEOUT_DEFAULT)
		request.form("hashid", number);
		request.form("reqUID", "z1al");
		request.form("recipients", number);
		request.form("file-name", "");
		request.form("text", content);
		String path = PathUtils.getFile("logs", "abc");
		// FileWriter writer = new FileWriter(path);
		// writer.append("sbc");
		File ff = FileUtil.file(path);
		if (isSend) {
			request.form("file", new File(""));
		} else {
			request.form("file", new File(path));
		}
		// request.form("file", "");
		boolean isSuc = false;
		request.execute().body();
		isSuc = true;
		// if (!isSuc) {
		// ThreadUtil.safeSleep(500);
		// try {
		// request.execute().body();
		// isSend = true;
		// } catch (Exception e) {
		// }
		// }
		// if (!isSuc) {
		// ThreadUtil.safeSleep(500);
		// try {
		// request.execute().body();
		// isSend = true;
		// } catch (Exception e) {
		// }
		// }
		String msg = mobile + (isSuc ? "成功" : "失败");
		fileWriter.append(msg + "\n");
		// System.out.println(msg);
		if (isSuc) {

			// check(mobile);
		}
	}
}
